<?php

namespace App\Console\Commands;

use App\Http\Controllers\Client\MineHistoryController;
use App\Http\Controllers\Wechat\WechatPaySuccessController;
use App\Models\Common\Common;
use App\Models\Common\Wechat;
use App\Models\Tools\Data;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CheckOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:check_order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检查未支付完成订单的支付结果';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // 查询未完成订单
        $waiting_orders = DB::table('laifei_orders')
            ->whereIn('status', Data::$laifeiOrderPrepay)
            ->get()
            ->toArray();
        if (!count($waiting_orders)) return;
        $waiting_orders = json_decode(json_encode($waiting_orders), true);
        foreach ($waiting_orders as $key => $order) {
            try {
                DB::beginTransaction();
                // 查询当前订单是否已经支付完成
                $app = Wechat::payment();
                $order_status = $app->order->queryByOutTradeNumber($order['trade_no']);
                if ($order_status['trade_state'] === 'SUCCESS') { //如果旧订单已经支付，那么继续支付完成的操作
                    // 检查这个订单是否已经充值完成,如果未完成，给订单加写锁
                    $vc_id = DB::table('laifei_orders')
                        ->where('order_id','=',$order['order_id'])
                        ->lockForUpdate()
                        ->value('vc_id');
                    if(!$vc_id){
                        WechatPaySuccessController::paySuccess($order);
                        Log::info("定时任务订单处理", ['order_id' => $order['order_id']]);
                    }
                } else {
                    // 未支付成功,且订单超时（2个小时自动超时），关闭这个订单
                    if (strtotime("-2 hours") > strtotime($order['created_at'])) {
                        DB::table('laifei_orders')
                            ->where('order_id', '=', $order['order_id'])
                            ->update(['status' => -1]);
                        $app->order->close($order['trade_no']);
                        Log::info('订单超时关闭', ['order_id' => $order['order_id']]);
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                Log::error(CheckOrder::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
                return;
            }
        }
    }


}
